package com.ewili.x.special.service.data.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ewili.framework.utils.HttpClientUtils;
import com.ewili.x.special.dao.inter.ThemeDao;
import com.ewili.x.special.dao.inter.ThemeStockDao;
import com.ewili.x.special.entity.Theme;
import com.ewili.x.special.entity.ThemeStock;
import com.ewili.x.special.service.data.inter.ThemeStockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ThemeStockServiceImpl implements ThemeStockService {

    @Autowired
    private ThemeDao themeDao;

    @Autowired
    private ThemeStockDao themeStockDao;

    @Override
    public void spide() {
        themeStockDao.deleteAll();
        List<Theme> themes = themeDao.findAll();
        for (Theme theme : themes) {
            String themeCode = theme.getThemeCode();
            String url = "http://quote.eastmoney.com/zhuti/api/themerelatestocks?CategoryCode=" + themeCode + "&startIndex=1&pageSize=19999";
            this.spideStock(url);
        }
    }

    private void spideStock(String url) {

        String content = HttpClientUtils.getContent(url, 300000, 300000);

        JSONObject object = JSONObject.parseObject(content);
        JSONArray objectArr = object.getJSONArray("result");
        JSONObject obj = objectArr.getJSONObject(0);
        JSONArray objArr = obj.getJSONArray("Data");
        for (int i = 0; i < objArr.size(); i++) {
            String value = objArr.getString(i);
            String[] lenArr = value.split("[|]", -1);

            String themeCode = lenArr[0] != null && !lenArr[0].isEmpty() && !lenArr[0].equals("") ? String.valueOf(lenArr[0]) : null;
            String stockCode = lenArr[1] != null && !lenArr[1].isEmpty() && !lenArr[1].equals("") ? String.valueOf(lenArr[1]) : null;
            String chName = lenArr[2] != null && !lenArr[2].isEmpty() && !lenArr[2].equals("") ? String.valueOf(lenArr[2]) : null;
            String reason = lenArr[5] != null && !lenArr[5].isEmpty() && !lenArr[5].equals("") ? String.valueOf(lenArr[5]) : null;

            ThemeStock themeStock = new ThemeStock();
            themeStock.setChName(chName);
            themeStock.setReason(reason);
            themeStock.setStockCode(stockCode);
            themeStock.setThemeCode(themeCode);
            themeStockDao.save(themeStock);
        }


    }

}
